<?php

define('AF_SESSION_DIR', '/tmp');
define('AF_SESSION_PREFIX', 'af_session_');
define('AF_SESSION_EXT', '.ser');

class AFSessionModule extends AFModule
{
	private $vars = array();
	private $token = NULL;

	public function __construct()
	{
	}

	public function init()
	{
		$systemId = $this->systemId();

		if(isset($_COOKIE[$systemId]) && ($this->load($_COOKIE[$systemId])))
		{
			$this->token = $_COOKIE[$systemId];
		}
		else
		{
			$newToken = $this->newToken();
			$this->save($newToken);
			setcookie($systemId, $newToken, time() + 86400*7, AF()->getPath());
			$this->token = $newToken;
		}
	}

	private function systemId()
	{
		return md5($_SERVER['SERVER_NAME'] . __FILE__ . AF()->getPath());
	}

	private function newToken()
	{
		return md5((isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:'') . $_SERVER['REMOTE_ADDR'] . microtime(TRUE) . rand(1, 1000000));
	}

	private function save($token)
	{
		$f = fopen(AF_SESSION_DIR . AF_SEP . AF_SESSION_PREFIX . $this->systemId() . '_' . $token . AF_SESSION_EXT, 'w');
		fwrite($f, serialize($this->vars));
		fclose($f);
	}

	private function load($token)
	{
		$data = @file_get_contents(AF_SESSION_DIR . AF_SEP . AF_SESSION_PREFIX . $this->systemId() . '_' . $token . AF_SESSION_EXT);
		if(!$data)
		{
			return FALSE;
		}
		else
		{
			$this->vars = unserialize($data);
			return TRUE;
		}
	}

	public function has($key)
	{
		return isset($this->vars[$key]);
	}

	public function get($key)
	{
		if(!$this->has($key))
		{
			return NULL;
		}
		return $this->vars[$key];
	}

	public function __get($key)
	{
		return $this->get($key);
	}

	public function set($key, $value)
	{
		$this->vars[$key] = $value;
	}

	public function __set($key, $value)
	{
		$this->set($key, $value);
	}

	public function __destruct()
	{
		$this->save($this->token);
	}
}

?>
